// ChinaChess.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "ChinaChess.h"
#include <commdlg.h>
#include <vector>
#include <iostream>
#include <conio.h>
#include <fstream>
#include <sstream>
#include "FileUtility.h"



#pragma comment(lib, "Gdiplus.lib")

#define MAX_LOADSTRING 100
#define CELL_NAME "cell"
#define PIX_EXTENSION ".png"
#define PIX_DIR "pixmaps/"
#define BOARD_WIDTH 8;
#define BOARD_HEIGHT 8;

using namespace Gdiplus;

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

/* Declare handle for basic control */
HWND hPushButton, hDefPushButton;
HWND hLabelControl;
HWND hListBoxControl;

HFONT hFont; 

HWND		g_HandleWindow;
HINSTANCE   g_hInstance; 


Board *mainBoard;
list<string>plsListLog;
LPWSTR fileName;
int countNumberMove =0 ;
POINT currPos;
POINT newPos;
int tick =0;
int sizeLog;
// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

/* Declare prototypes */
void CREATE_BUTTON();
void CREATE_LABELCONTROL();
void CREATE_LISTBOXCONTROL();


//Declare method here
bool IsLegitClick(int x, int y, int &rowClicked, int &colClicked);
void Initialize();
void InitializeBoard(HWND hWnd,HINSTANCE hInst,HDC hdc,int x, int y,int height, int width, int id);
void InitializeChessPiece();
void ClearUp();
string wstrtostr(const std::wstring &wstr) ;
void save(string filename,vector <string> liststep);
vector <string> load(string filename);
void ReadLineAuto(HWND hWnd,string filename);
void getLineinfoRedMove(string line);
void getLineinfoBlackMove(string line);
list<string> CopyFileToList(string filename);
void ReadLineAt(list<string>plsListLog, int at);
//
VOID OnPaint(HDC hdc)
{
	Gdiplus::Graphics graphics(hdc);
	mainBoard->Draw(graphics);
	
}

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	HACCEL hAccelTable;
	//Initialize GID+
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_CHINACHESS, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CHINACHESS));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	GdiplusShutdown(gdiplusToken);
	return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= NULL;//CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CHINACHESS));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(DKGRAY_BRUSH);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_CHINACHESS);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable
   //Inintialize chess board and pieces
   Initialize();
  
   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW ,250
      , 0, 800, 730, NULL, NULL, hInstance, NULL);
   if (!hWnd)
   {
      return FALSE;
   }
    
   //nCmdShow = SW_MAXIMIZE;
   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	g_HandleWindow = hWnd;
	PAINTSTRUCT ps;
	HDC hdc;
	//hdc = BeginPaint(hWnd, &ps);
	bool result = false;
	POINT clickPoint = POINT();
	
	RECT rect;
	rect.left=40;
	rect.top=40;
	rect.right = 540;
	rect.bottom = 600;
	
	char szFileName[MAX_PATH] = "";
	
	static LPWSTR abcs;
	static OPENFILENAME ofn;
    // LPFINDREPLACE    pfr ;
	switch (message)
	{
	case WM_CREATE:
	
		CREATE_BUTTON();
		//CREATE_LABELCONTROL();
		CREATE_LISTBOXCONTROL();
		//PopFileInitialize (hWnd) ;
		//set timer 
		//EnableWindow(HWND(ID_BUTTON_DEFPUSH_NEXT), false);
		break;
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		
		case IDM_FILE_OPEN:  
			{
				
				
				OPENFILENAME ofn;
				ZeroMemory(&ofn, sizeof(ofn));
				ZeroMemory(&szFileName, sizeof(szFileName));
				ofn.lStructSize = sizeof(ofn); 
				ofn.hwndOwner = NULL;
				ofn.lpstrFilter = (LPCWSTR)L"Type (*.team1)\0*.team1";
				ofn.lpstrFile = (LPWSTR)szFileName;
				ofn.nMaxFile = MAX_PATH;
				ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;				
				ofn.lpstrDefExt = (LPCWSTR)L"txt";
				if(GetOpenFileName(&ofn))
				{
					CREATE_LISTBOXCONTROL();
					 abcs = (LPWSTR) ofn.lpstrFile;
					 plsListLog = CopyFileToList(wstrtostr(abcs));
					//vector<string> abc = load(wstrtostr(abcs));
					
				}
				sizeLog = plsListLog.size();
				Initialize();				
				InvalidateRect(hWnd,NULL,TRUE);
				
				
				//mainBoard->MoveAuto(currPos,newPos);
				break;
		}
		case IDM_FILE_SAVE:
			{
				
				char szFileName[MAX_PATH] = "";
				ZeroMemory(&ofn, sizeof(ofn));
				ZeroMemory(&szFileName, sizeof(szFileName));
				ofn.lStructSize = sizeof(ofn); 
				ofn.hwndOwner = NULL;
				ofn.lpstrFilter = (LPCWSTR)L"Type (*.team1)\0*.team1";
				ofn.lpstrFile = (LPWSTR)szFileName;
				ofn.nMaxFile = MAX_PATH;
				ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
				ofn.lpstrDefExt = (LPCWSTR)L"txt";
				if(GetSaveFileName(&ofn))
				{
					LPWSTR abc = (LPWSTR) ofn.lpstrFile;
					save(wstrtostr(abc),mainBoard->plszLstLog);
				}

				break;
			}
		case ID_BUTTON_STARTAUTO:
			{
				ReadLineAt(plsListLog, countNumberMove);
				SetTimer (hWnd, ID_TIMER, 500, NULL) ;

				break;
			}
		case ID_BUTTON_DEFPUSH_FIRST:
			{
				break;
			}
		case ID_BUTTON_DEFPUSH_PREV:
			{
				Initialize();	
				int i;
				for(i = 0; i< countNumberMove-1; i++)
				{
					ReadLineAt(plsListLog, i);
					mainBoard->ChoisePieceAuto(currPos);
					mainBoard->MoveAuto(currPos,newPos);
				}

				if(countNumberMove >0)
					countNumberMove --;
				InvalidateRect(hWnd,&rect,TRUE);
				break;
			}
		case  ID_BUTTON_DEFPUSH_NEXT:
			{
				if(countNumberMove == sizeLog)
				{	
					//KillTimer(hWnd,ID_TIMER);
					WCHAR* msg = L"HET ROI NHE'";
					MessageBox(NULL,msg, (LPCTSTR)L"Msg", MB_OK | MB_ICONERROR);
					return 0;
				}
				ReadLineAt(plsListLog, countNumberMove);
				mainBoard->ChoisePieceAuto(currPos);
				mainBoard->MoveAuto(currPos,newPos);

				countNumberMove++;

				InvalidateRect(hWnd,&rect,TRUE);
				break;
			}
		case  ID_BUTTON_DEFPUSH_LAST:
			{
				break;
			}
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
			break;

		}
		break;
	case WM_LBUTTONDOWN:
		clickPoint.y = LOWORD(lParam);
		clickPoint.x = HIWORD(lParam);
		mainBoard->Click(hListBoxControl, clickPoint);
		InvalidateRect(hWnd,NULL,TRUE);
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		//Initialize background Board
		InitializeBoard(hWnd,hInst,hdc,ConstValue::padding,ConstValue::padding,760,619,12344);
		//Initialize background Current Move
		if(TRUE == mainBoard->players.GetCurrentTurn())
			InitializeBoard(hWnd,hInst,hdc,ConstValue::padding+550,ConstValue::padding+40,200,104,12346);
		else
		{
			InitializeBoard(hWnd,hInst,hdc,ConstValue::padding+550,ConstValue::padding+40,200,104,12347);
		}
		//Initialize background listBox
		InitializeBoard(hWnd,hInst,hdc,ConstValue::padding+550,ConstValue::padding+165,200,415,12345);
		OnPaint(hdc);
		EndPaint(hWnd, &ps);
		break;
	case WM_TIMER:
		{
			

			if(3 == tick)
			{
				countNumberMove++;
				if(countNumberMove == sizeLog)
				{	
					KillTimer(hWnd,ID_TIMER);
					WCHAR* msg = L"HET ROI NHE'";
					MessageBox(NULL,msg, (LPCTSTR)"Msg", MB_OK | MB_ICONERROR);
					return 0;
				}
				ReadLineAt(plsListLog, countNumberMove);
				tick =0;
			}
			
			switch (wParam) 
			{ 
				case ID_TIMER: 
					{
						if(0 == tick )
						{	
							mainBoard->ChoisePieceAuto(currPos);
						}
						if(1 == tick )
						{
							mainBoard->MoveAuto(currPos,newPos);
						}

						InvalidateRect(hWnd,&rect,TRUE);
						break;
					}
				default:
					break;
			}

			//InvalidateRect (hWnd, &rect, TRUE) ;
			tick ++;		
			break;
		}
	case WM_DESTROY:
		KillTimer (hWnd, ID_TIMER);
		KillTimer (hWnd, ID_TIMER1);
		ClearUp();
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}

/* This is a common function. This function creates one control based on input parameter */
void Create_Control(HWND &controlHandle,
					HWND hParent, 
					LPCTSTR lpClassName, 
					int ID , 
					LPCTSTR caption, 
					DWORD dwStyle, 
					int Position_X, 
					int Position_Y, 
					int nWidth, 
					int nHeight)
{

    // Short form of CreateWindowEx function
	controlHandle = CreateWindowEx(	NULL,
									lpClassName,			
									caption,		
									dwStyle,			
									Position_X, 
									Position_Y,			
									nWidth, 
									nHeight,
									(hParent==NULL)?	g_HandleWindow:hParent, 
									(HMENU) ID,			
									g_hInstance,
									NULL );
	// set default font
	SendMessage(	controlHandle,
					WM_SETFONT,
					(WPARAM)hFont,
					0 );
	//SendMessage(controlHandle,WM_SETFONT,(WPARAM)hFont,0);
	if(!controlHandle) MessageBox(g_HandleWindow,L"Create control is failed",L"",0);	
	
}

void CREATE_BUTTON()
{

	Create_Control( hPushButton,	/* Handle */
					NULL,		/* Handle of parent */
					L"Button",  /* class name	*/
					ID_BUTTON_DEFPUSH_FIRST , /* ID		*/
					L"<<",		/* Caption/Title */
					BUTTON_STYLE_PUSHBUTTON, /* Style */
					80,		/* Position X */
					580+ConstValue::xBeginDraw,		/* Position Y */
					60,		/* Width      */
					40 );		/* Height     */	
		Create_Control( hPushButton,	/* Handle */
					NULL,		/* Handle of parent */
					L"Button",  /* class name	*/
					ID_BUTTON_DEFPUSH_PREV , /* ID		*/
					L"<",		/* Caption/Title */
					BUTTON_STYLE_PUSHBUTTON, /* Style */
					160,		/* Position X */
					580+ConstValue::xBeginDraw,		/* Position Y */
					60,		/* Width      */
					40 );		/* Height     */		
		Create_Control( hPushButton,	/* Handle */
					NULL,		/* Handle of parent */
					L"Button",  /* class name	*/
					ID_BUTTON_DEFPUSH_NEXT , /* ID		*/
					L">",		/* Caption/Title */
					BUTTON_STYLE_PUSHBUTTON, /* Style */
					240,		/* Position X */
					580+ConstValue::xBeginDraw,		/* Position Y */
					60,		/* Width      */
					40 );		/* Height     */	
	Create_Control( hDefPushButton,
					NULL, 
					L"Button", 
					ID_BUTTON_DEFPUSH_LAST , /* ID		*/ 
					L">>", 
					BUTTON_STYLE_DEFPUSHBUTTON, 
					320, 
					580+ConstValue::xBeginDraw, 
					60, 
					40 );	
	Create_Control( hDefPushButton,
					NULL, 
					L"Button", 
					ID_BUTTON_STARTAUTO , 
					L"START AUTO", 
					BUTTON_STYLE_DEFPUSHBUTTON, 
					610, 
					580+ConstValue::xBeginDraw, 
					100, 
					40 );	

}

/* Create label control */
void CREATE_LABELCONTROL()
{
	  HFONT	    font;
	font =CreateFont( 15, 5, 0, 0, 900, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("Tahoma"));
	COLORREF Static = RGB(255, 25, 2);
	for(int i=16; i>=0;i=i-2)
	{
		Create_Control( hLabelControl,	/* Handle */
					NULL,//NULL,		/* Handle of parent */
					L"Static",  /* class name	*/
					ID_LABEL_CONTROl, /* ID		*/
					L"8"	,	/* Caption/Title */
					LABEL_STYLE, /* Style */
					ConstValue::xBeginDraw+26.5+26.5*i,		/* Position X */
					ConstValue::xBeginDraw-10,		/* Position Y */
					15,		/* Width      */
					15 );		/* Height     */
	}
	for(int i=0; i<=17;i=i+2)
	{
		Create_Control( hLabelControl,	/* Handle */
					NULL,//NULL,		/* Handle of parent */
					L"Static",  /* class name	*/
					ID_LABEL_CONTROl, /* ID		*/
					L"2"	,	/* Caption/Title */
					LABEL_STYLE, /* Style */
					ConstValue::xBeginDraw+26.5+26.5*i,		/* Position X */
					550+ConstValue::xBeginDraw,		/* Position Y */
					15,		/* Width      */
					15 );		/* Height     */
	}
	Create_Control( hLabelControl,	/* Handle */
					NULL,//NULL,		/* Handle of parent */
					L"Static",  /* class name	*/
					ID_LABEL_CONTROl , /* ID		*/
					L"NEXT MOVE",		/* Caption/Title */
					LABEL_STYLE, /* Style */
					550+ConstValue::xBeginDraw,		/* Position X */
					ConstValue::xBeginDraw,		/* Position Y */
					120,		/* Width      */
					30 );		/* Height     */
	Create_Control( hLabelControl,	/* Handle */
					NULL,//NULL,		/* Handle of parent */
					L"Static",  /* class name	*/
					ID_LABEL_CONTROl , /* ID		*/
					L"RED ",		/* Caption/Title */
					LABEL_STYLE, /* Style */
					550+ConstValue::xBeginDraw,		/* Position X */
					ConstValue::xBeginDraw+30,		/* Position Y */
					120,		/* Width      */
					30 );		/* Height     */
}

void CREATE_LISTBOXCONTROL()
{	

	Create_Control( hListBoxControl,	/* Handle */
					NULL,//NULL,		/* Handle of parent */
					L"LISTBOX",  /* class name	*/
					ID_LISTBOX_CONTROl , /* ID		*/
					L"listbox control",		/* Caption/Title */
					LISTBOX_STYLE, /* Style */
					562+ConstValue::padding,		/* Position X */
					ConstValue::padding+255,		/* Position Y */
					175,		/* Width      */
					275);		/* Height     */
	/* Initial item for listbox control */
	
    
	//SendMessage(hListBoxControl, LB_ADDSTRING, 0, (LPARAM)(LPCTSTR)TEXT("Item3"));
    //SendMessage(hListBoxControl, LB_ADDSTRING, 0, (LPARAM)(LPCTSTR)TEXT("Item4"));
}

bool IsLegitClick(int x, int y, int &rowClicked, int &colClicked)
{
	//Calculate the distance between 2 cell.
	int cellDistance = ConstValue::padding + ConstValue::cellHeightWidth;
	//Minus the space that is used to draw cell in the middle of the form
	x = x - ConstValue::xBeginDraw;
	y= y - ConstValue::yBeginDraw;
	//
	int leftCell = x/ cellDistance;
	int rightCell = leftCell + 1;
	int leftCellPlusSpace = leftCell*cellDistance + ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	int leftCellMinusSpace = leftCell*cellDistance - ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	int rightCellPlusSpace = rightCell*cellDistance + ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	int rightCellMinusSpace = rightCell*cellDistance - ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	//
	int aboveCell = y/cellDistance;
	int belowCell = aboveCell + 1;
	int aboveCellPlusSpace = aboveCell*cellDistance + ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	int aboveCellMinusSpace = aboveCell*cellDistance - ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	int belowCellPlusSpace = belowCell*cellDistance + ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	int belowCellMinusSpace = belowCell*cellDistance - ConstValue::clickableSpace + ConstValue::cellHeightWidth/2;
	bool result = false;
	//Condition so that user can't click outside board
	if(leftCell>0 && rightCell <= (BoardInfo::col +1) && aboveCell>0 && belowCell <= (BoardInfo::row + 1))
	{
		if(x<leftCellPlusSpace && x>leftCellMinusSpace)
		{
			colClicked = leftCell -1;
			result = true;
		}
		else if(x<rightCellPlusSpace && x>rightCellMinusSpace)
		{
			colClicked = rightCell -1;
			result = true;
		}
		if(result == true)
		{
			if(y<aboveCellPlusSpace &&  y> aboveCellMinusSpace)
			{
				rowClicked = aboveCell -1;
				return true;
			}
			else if(y<belowCellPlusSpace && y>belowCellMinusSpace)
			{
				rowClicked = belowCell -1;
				return true;
			}
		}
	}
	return false;
}

void Initialize()
{
	mainBoard = new Board();
	//mainBoard->SetBoard(ConstValue::pixDir + "ixiangqi.png");
	mainBoard->InitializeChessPiece();
	/*InitializeBoardCell();
	InitializeChessPiece();*/
}

void ClearUp()
{
	/*for(int y=0; y< BoardInfo::row; y++)
		{
			for(int x=0; x<BoardInfo::col; x++)
			{
				cell[y][x].~BoardCell();
				free(pieces[y][x]);
			}
		}*/
}

//vector <string> load(string filename)
//{
//	wchar_t portName[20];
//	vector <string> listtemp;
//	string word;
//    ifstream wordfile(filename);
//	std::string str; 
//    while (std::getline(wordfile, str))
//    {
//
//		wstring wideusername;
//		for(int i = 0; i < str.length(); ++i)
//		  wideusername += wchar_t( str[i] );
//		const wchar_t* your_result = wideusername.c_str();
//		SendMessage(hListBoxControl, LB_ADDSTRING, 0, (LPARAM)your_result);
//    }
//	return listtemp;
//}

void  ReadLineAuto(HWND hWnd, string filename)
{
	string line;
	//int count =0;
	//int newPosX, newPosY,currPoxX, currPoxY;

	ifstream readfile(filename);	
	while (!readfile.eof())
	{
		getline(readfile,line,'\n');
		//SendMessage(hListBoxControl, LB_ADDSTRING, 0, (LPARAM)FileUtility::GetInstance()->ConvertToWcharT(line));
		//getLineinfo(line);
	}

}

list<string> CopyFileToList(string filename)
{
	list<string> listTemp;
	string line;
	ifstream readfile(filename);	
	if(!readfile)
	{
		WCHAR* msg = L"Can not open file'";
		MessageBox(NULL,msg, (LPCTSTR)"Msg", MB_OK | MB_ICONERROR);

	}
	while (!readfile.eof())
	{
		getline(readfile,line,'\n');
		if( 0 == line.length())
		{

		}
		else
		{
			listTemp.push_back(line);
			SendMessage(hListBoxControl, LB_ADDSTRING, 0, (LPARAM)FileUtility::GetInstance()->ConvertToWcharT(line));
		}
		
	}
	return listTemp;
}

void ReadLineAt(list<string>plsListLog, int at)
{
	list<string>::const_iterator it;
	int count =0;
	for(it = plsListLog.begin(); it != plsListLog.end() ; it++)
	{
		if(count > at)
		{
			return;
		}
		if(count == at)
		{
			if(0 == at%2) // le
				getLineinfoRedMove((*it));
			else
			{
				getLineinfoBlackMove((*it));
			}
		}
		count++;
	}
}

void getLineinfoRedMove(string line)
{
	list<POINT> plzPointLog;
	//int newPosX, newPosY,currPoxX, currPoxY;

	vector<string> listtemp;
	vector<string>::const_iterator it;
	std::istringstream temp(line);
	string foo;
	while(temp>>foo) 
	{
		listtemp.push_back(foo);
		cout<<foo<<"\n";			

	}		
	it = listtemp.begin()+1;
	if(4 == (*it).size())
	{
		cout<<(*it).substr(1,2)<<"\n";
		std::istringstream ((*it).substr(1,1)) >> currPos.x;
		std::istringstream ((*it).substr(2,1)) >> currPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}
	if(5 == (*it).size())
	{	
		cout<<(*it).substr(1,3)<<"\n";
		std::istringstream ((*it).substr(1,2)) >> currPos.x;
		std::istringstream ((*it).substr(3,1)) >> currPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}

	it = listtemp.end()-1;

	if(2 == (*it).size())
	{

		std::istringstream ((*it).substr(0,1)) >> newPos.x;
		std::istringstream ((*it).substr(1,1)) >> newPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}
	if(3 == (*it).size())
	{	

		std::istringstream ((*it).substr(0,2)) >> newPos.x;
		std::istringstream ((*it).substr(2,1)) >> newPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}
	//}
	currPos.x =currPos.x-1;
	currPos.y = currPos.y-1;
	newPos.x = newPos.x-1;
	newPos.y = newPos.y -1;
	
	//mainBoard->ChoisePieceAuto(currPos);
	//InvalidateRect (hWnd, NULL, TRUE) ;

	//mainBoard->MoveAuto(currPos,newPos);
	//return newPos;
}

void getLineinfoBlackMove(string line)
{
	list<POINT> plzPointLog;
	//int newPosX, newPosY,currPoxX, currPoxY;

	vector<string> listtemp;
	vector<string>::const_iterator it;
	std::istringstream temp(line);
	string foo;
	while(temp>>foo) 
	{
		listtemp.push_back(foo);
		cout<<foo<<"\n";			

	}		
	it = listtemp.begin()+1;
	if(4 == (*it).size())
	{
		cout<<(*it).substr(1,2)<<"\n";
		std::istringstream ((*it).substr(1,1)) >> currPos.x;
		std::istringstream ((*it).substr(2,1)) >> currPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}
	if(5 == (*it).size())
	{	
		cout<<(*it).substr(1,3)<<"\n";
		std::istringstream ((*it).substr(1,2)) >> currPos.x;
		std::istringstream ((*it).substr(3,1)) >> currPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}

	it = listtemp.end()-1;

	if(2 == (*it).size())
	{

		std::istringstream ((*it).substr(0,1)) >> newPos.x;
		std::istringstream ((*it).substr(1,1)) >> newPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}
	if(3 == (*it).size())
	{	

		std::istringstream ((*it).substr(0,2)) >> newPos.x;
		std::istringstream ((*it).substr(2,1)) >> newPos.y;
		//cout<<currPoxX<<","<<currPoxY<<endl;
	}
	//}
	currPos.x = BoardInfo::row - currPos.x;
	currPos.y = BoardInfo::col -currPos.y;
	newPos.x = BoardInfo::row - newPos.x;
	newPos.y = BoardInfo::col - newPos.y;

	//mainBoard->ChoisePieceAuto(currPos);
	//InvalidateRect (hWnd, NULL, TRUE) ;

	//mainBoard->MoveAuto(currPos,newPos);
	//return newPos;
}


void save(string filename,vector <string> liststep)
{
    ofstream log (filename);
    if(! log.is_open())
    {
        //loi open file
    }
    else 
	{
		  for(int i=0;i<liststep.size();i++)
			  log<<liststep.at(i)<<'\n';
	}
	log.close();
}

std::string wstrtostr(const std::wstring &wstr)
{
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

void InitializeBoard(HWND hWnd,HINSTANCE hInst,HDC hdc,int x, int y,int height, int width, int id)
{
	HDC MemDCLoadBitmap;  
	HBITMAP  bmpLoadBitmap;
	bmpLoadBitmap = LoadBitmap(hInst,MAKEINTRESOURCE(id));
			if (bmpLoadBitmap!= NULL)
			{
				// Create a memory device compatible with the above DC variable
				MemDCLoadBitmap = CreateCompatibleDC(hdc);
        
				// Select the new bitmap
				SelectObject(MemDCLoadBitmap, bmpLoadBitmap);

				// Copy the bits from the memory DC into the current dc
				BitBlt(hdc, x, y , height , width , MemDCLoadBitmap, 0, 0, SRCCOPY);

				// Restore the old bitmap
				DeleteDC(MemDCLoadBitmap);
				DeleteObject(bmpLoadBitmap);
			}
			else
			{
				MessageBox(hWnd, L"Cannot Load Bitmap. Bitmap not found", L"Load bitmap",MB_OK);
			}
}